import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class Customer  implements Runnable  
{
	Theater theater;
	Thread customerThread;
	String choice;
	String customerid;
	Movie bookedMovie;
	boolean killthread;
	
	public Customer (Theater T,String customerid,String choice )
	{ 
    	this.theater=T;
    	customerThread= new Thread(this);
    	this.choice=choice;
    	this.customerid=customerid;
    	customerThread.start();	
	}

	
	public void run() 
	{
		
		Book(choice);

		if(killthread)
			return;
		
		bookedMovie.barrier.addToBarrier();
		
		
		theater.Printer(customerid+" finished watching "+bookedMovie.moviename+" and has left");
		theater.updateSchedule();
		 	
	}

			



	public void Book(String moviename)
	{
		 
		
		theater.mutex.down();
		 
		if(theater.getIndex(moviename)!=-1)										//is the movie already in the play list?
		{ 
			theater.mutex.up();
			 
			theater.mutex1.down();
  
					if(!theater.playList.get(theater.getIndex(moviename)).isFull())			//if yes is there space in the movie?
					{
						theater.playList.get(theater.getIndex(moviename)).addSpectator(this);
						theater.updateSchedule();
						 
						theater.mutex1.up();
					}
					else
					{
							if(theater.isLatestMovie(theater.getIndex(moviename)))			//before creating a new movie, we should check that the last movie wasn't the same one
							{
								theater.mutex1.up(); 
								
								if(theater.getIndex(moviename)==9 || theater.getIndex(moviename)==10)	
									leaveTheater("the movie can no longer be shown today");//" the movie can no longer be shown today");
								else
								{
									theater.Consectutive++;
									theater.Printer(customerid+" is waiting for a slot to book "+moviename);
									theater.consectutiveMovies.down();
									theater.Consectutive--;								
				
									Book(moviename);
									
								
								}
							}
							else
							{
								if(!theater.addMovie( new Movie(moviename,this,theater) ))			//are there already 10 movies showing today?
									leaveTheater(" no more movies can be shown today");//" no more movies can be shown today");	
								 
								theater.mutex1.up();
								
							}	
					}
		}
		else
		{
			if(!theater.addMovie(new Movie(moviename,this,theater)))			//are there already 10 movies showing today?
				leaveTheater(" no more movies can be shown today");//" no more movies can be shown today");	
			
			 
			theater.mutex.up();
		}
			
	}
	
	
	
	private void pause() 
	{

		try 
		{
			Thread.sleep(500);
		} catch (InterruptedException e) {}
		
	}
	
	public  void leaveTheater(String reason)
	{
		
		 theater.Printer(customerid+" has left the theater, reason:"+reason);
		 killthread=true;
	
		  		 		 
	}
 
	

}
